import React, {useState, useEffect, useMemo} from 'react';
import {Row, Col, Spin, Empty, Select} from 'antd';
import {cloneDeep} from 'lodash';
import {usePersistFn} from 'ahooks';

import {getChartsForDetail} from '~/service/liveMonitor';
import TrendChart from '../../common/trendChart';
import TrendChartDoubleY from '../../common/trendChartDoubleY';
import CommonCard from '../../common/CommonCard';
import './index.styl';
import {ClientList, chartMap} from '../../config.js';
import EventsDrawer from './EventsDrawer';

const {Option} = Select;

const handleStreamMediaSeries = series => series.map((item, index) => {
    if (index !== 0) {
        item.yAxisIndex = 1;
    }
    return item;
});

const withApiChart = Element => props => {
    const {
        params,
        client,
        title,
        setFormLoading,
        ...restProps
    } = props;
    const [lineUnit, setLineUnit] = useState({});
    const [loading, setLoading] = useState(false);
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [drawerParams, setDrawerParams] = useState('');

    const run = usePersistFn(
        (params, client, title) => {
            const dimensionAndValues = cloneDeep(params);
            if (client !== undefined) {
                const clientParams = {
                    dimensionId: 'LiveRoomDetail_select_client_type',
                    dimensionName: 'client_type',
                    value: [client ?? '']
                };
                dimensionAndValues.push(clientParams);
            }


            const {dashBoardId, unitId} = chartMap.get(title);
            const dashBoardList = [
                {
                    dashBoardId,
                    dashBoardName: dashBoardId
                }
            ];

            const resultParams = {
                dashBoardList,
                dimensionAndValues
            };
            setFormLoading(true);
            setLoading(true);
            getChartsForDetail(resultParams).then(res => {
                const {
                    data
                } = res;
                let lineUnit = {};

                if (data && data[dashBoardId] && data[dashBoardId][unitId]) {
                    lineUnit = data[dashBoardId][unitId];
                }

                setLineUnit(lineUnit);
                setFormLoading(false);
                setLoading(false);
            });
        }
    );

    useEffect(() => {
        if (params.length > 0) {
            run(params, client, title);
        }
    }, [params, client, run, title]);

    const handleClick = values => {
        setDrawerVisible(true);
        const {name} = values;
        setDrawerParams(name);
    };

    return (
        <>
            {
                (Object.keys(lineUnit || {})?.length > 0 && lineUnit?.chart)
                    ? (
                        <Element
                            {...params}
                            {...restProps}
                            chartData={lineUnit}
                            loading={loading}
                            handleClick={handleClick}
                        />
                    )
                    : <Spin spinning={loading}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></Spin>
            }
            {
                drawerVisible && (
                    <EventsDrawer
                        visible={drawerVisible}
                        setVisible={setDrawerVisible}
                        params={drawerParams}
                        searchParams={params}
                        setDrawerParams={setDrawerParams}
                    />
                )
            }
        </>
    );
};

// const DoubleChart = withApiChart(TrendChartDoubleY);


const ChartsContainer = ({client, setClient, setFormLoading, ...restProps}) => {

    const DoubleChart = useMemo(() => withApiChart(TrendChartDoubleY), []);
    const SingleChart = useMemo(() => withApiChart(TrendChart), []);


    const handleClientChange = usePersistFn(value => {
        setClient(value ?? '');
    });

    return (
        <div>
            <div className="detail-h4-title">
                学生趋势
            </div>
            <div className="detail-client-server">
                客户端：
                <Select
                    onChange={handleClientChange}
                    value={client}
                    getPopupContainer={node => node.parentNode}
                >
                    {
                        ClientList.map(item => (
                            <Option value={item.value} key={item.value}>
                                {item.name}
                            </Option>
                        ))
                    }
                </Select>
            </div>
            <Row gutter={8} className="trend-charts">
                <Col span={12}>
                    <CommonCard title="学生人数">
                        <SingleChart
                            {...restProps}
                            client={client}
                            title="学生人数"
                            rightYAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
                <Col span={12}>
                    <CommonCard title="流媒体连接">
                        <DoubleChart
                            {...restProps}
                            client={client}
                            title="流媒体连接"
                            rightYAxisLabel={{formatter: '{value}'}}
                            handleSeries={handleStreamMediaSeries}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
                <Col span={12}>
                    <CommonCard title="学生卡顿">
                        <DoubleChart
                            {...restProps}
                            client={client}
                            title="学生卡顿"
                            rightYAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
                <Col span={12}>
                    <CommonCard title="聊天问题">
                        <SingleChart
                            {...restProps}
                            title="聊天问题人数"
                            client={client}
                            yAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
            </Row>
            <div className="detail-h4-title">
                老师趋势
            </div>
            <Row gutter={8} className="trend-charts">
                <Col span={12}>
                    <CommonCard title="老师CPU和内存">
                        <DoubleChart
                            {...restProps}
                            title="老师CPU和内存"
                            rightYAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
                <Col span={12}>
                    <CommonCard title="老师丢包率">
                        <SingleChart
                            {...restProps}
                            title="老师丢包率"
                            yAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            setFormLoading={setFormLoading}
                            gridBottom={60}
                        />
                    </CommonCard>
                </Col>
                <Col span={12}>
                    <CommonCard title="老师帧率和码率">
                        <DoubleChart
                            {...restProps}
                            title="老师帧率和码率"
                            rightYAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
                <Col span={12}>
                    <CommonCard title="老师RTT">
                        <SingleChart
                            {...restProps}
                            title="老师RTT"
                            rightYAxisLabel={{formatter: '{value}'}}
                            dataZoom={false}
                            gridBottom={60}
                            setFormLoading={setFormLoading}
                        />
                    </CommonCard>
                </Col>
            </Row>
        </div>
    );
};

export default ChartsContainer;
